﻿//-----------------------------------------------------------------------
// <copyright file="AsAVisitorWhenILandInTheHomepageWithURLOrTenantKeyIShouldSeeTheTenantsTheming.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Utility.Tests.UI.Web.Behaviour.Home{    using System.Web;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Application.Configuration;
    using AbstractSaaSTemplate.Application.Routing;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Kernel.Factories;
    using AbstractSaaSTemplate.UI.Web;
    using AbstractSaaSTemplate.UI.Web.Controllers;
    using AbstractSaaSTemplate.UI.Web.Helpers;
    using AbstractSaaSTemplate.UI.Web.Models.Tenant;
    using AbstractSaaSTemplate.Utility.Tests.UI.Utilities;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using OOHM.Framework.Configuration;

    /// <summary>
    /// @14077783
    /// Ao acessar a landing page do sistema com o URL configurado para o tenant,
    /// ou com chave de URL relacionada ao tenant, o sistema deverá identificar o
    /// Tenant e ativar as configurações deste tenant para o sistema, sem que o
    /// usuário precise selecionar este tenant.
    /// </summary>
    [TestClass]
    public class TestFor0014077783
    {
        /// <summary>
        /// Gets or sets the base application controller.
        /// </summary>
        private TenantController TenantController { get; set; }

        /// <summary>
        /// Gets or sets the repository to operate 'Tenancy'.
        /// </summary>
        private ITenancyRepository TenancyRepository { get; set; }
        
        /// <summary>
        /// Prepares the unit test.
        /// </summary>
        [TestInitialize]
        public void Setup()
        {
            TestFor0013453151.EnsureInstallationIsComplete();

            var factory = new ApplicationFactory();

            this.TenantController = factory.CreateControllerFor<TenantController>();

            this.TenancyRepository = factory.CreateRepositoryFor<ITenancyRepository>();
        }

        /// <summary>
        /// @14077783
        /// Ao acessar a landing page do sistema com o URL configurado para o tenant,
        /// ou com chave de URL relacionada ao tenant, o sistema deverá identificar o
        /// Tenant e ativar as configurações deste tenant para o sistema, sem que o
        /// usuário precise selecionar este tenant.
        /// Passos da Mímica --------------------------------------------------
        /// 1) Configura template de URL com url de domínio customizado
        ///     Deve assegurar:
        ///     1.1) que ao acessar com url customizada, irá ver theming do Tenant
        /// 2) Configura template de URL com url de domínio padrão com key
        ///     Deve assegurar:
        ///     2.1) que acessar com url com token, irá ver theming do Tenant
        /// </summary>
        [TestMethod]
        public void AsAVisitorWhenILandInTheHomepageWithURLOrTenantKeyIShouldSeeTheTenantsTheming()
        {
            // 1)
            this.AssertThatCustomUrlsWillShowTheTenantsCustomization();

            // 2)
            this.AssertThatParameteredUrlsWillShowTheTenantsCustomization();
        }

        /// <summary>
        /// Creates a new tenant that can be used for testing.
        /// </summary>
        /// <param name="key">The key to differentiate one tenant from anohter.</param>
        /// <returns>Returns an instance of the form used to create tenants.</returns>
        private static CreateOrEditTenantForm NewTenantForTest(string key)
        {
            var model = new CreateOrEditTenantForm();
            model.KeyOrLocation = key;
            model.AdministratorEmailAddress = string.Concat("admin@", key, ".com");
            model.AdministratorFirstName = string.Concat(key, "-AdministratorFirstName");
            model.AdministratorLastName = string.Concat(key, "-AdministratorLastName");
            model.BillingAddressCity = string.Concat(key, "-BillingAddressCity");
            model.BillingAddressCountryCode = "55";
            model.BillingAddressLine1 = string.Concat(key, "BillingAddressLine1");
            model.BillingAddressLine2 = string.Concat(key, "BillingAddressLine2");
            model.BillingAddressLine3 = string.Concat(key, "BillingAddressLine3");
            model.BillingAddressPostalCode = "099990410";
            model.BillingAddressState = string.Concat(key, "BillingAddressState");
            model.CompanyName = string.Concat(key, "CompanyName");
            model.ContactAddressCity = string.Concat(key, "ContactAddressCity");
            model.ContactAddressCountryCode = "55";
            model.ContactAddressLine1 = string.Concat(key, "ContactAddressLine1");
            model.ContactAddressLine2 = string.Concat(key, "ContactAddressLine2");
            model.ContactAddressLine3 = string.Concat(key, "ContactAddressLine3");
            model.ContactAddressPostalCode = "099990410";
            model.ContactAddressState = string.Concat(key, "ContactAddressState");
            model.ContactPhoneAreaCode = "11";
            model.ContactPhoneExtension = "909";
            model.ContactPhoneNumber = "90903040";
            model.ContactUsesTheSameAddressAsBilling = false;
            model.DisplayName = string.Concat(key, "DisplayName");

            return model;
        }

        /// <summary>
        /// 1) Configura template de URL com url de domínio customizado
        ///     Deve assegurar:
        ///     1.1) que ao acessar com url customizada, irá ver theming do Tenant
        /// </summary>
        private void AssertThatCustomUrlsWillShowTheTenantsCustomization()
        {
            // we set the configuration to custom template "{0}"
            var configEntry = new { Key = ConfigurationKeys.AppBaseDomain, Value = "{0}" };

            // creates the configuration entry
            Configurator.AddOrUpdateConfigurationEntry(configEntry.Key, configEntry.Value);

            // here is the tenant key we want to find
            const string TenantKey = "www.tenant-0011.com.br";
            var tenantForTest = NewTenantForTest(TenantKey);

            // var we create the mvcApplication that will react to the request
            this.TenantController.MockForTesting(
                TenantKey,
                "ListTenants",
                HttpVerbs.Get);

            // create the tenant
            this.TenantController.CreateOrEditTenant(null, tenantForTest);

            // here we test if the tenant was correcly found from the url
            var mvcApplication = new MvcApplication(this.TenancyRepository);
            mvcApplication.ProcessRouteDataForTenancy();
            var containsTenantToken = HttpContext.Current.Request.RequestContext.RouteData.DataTokens.ContainsKey(DataTokens.ActiveTenant);
            Assert.IsTrue(containsTenantToken);

            var actualTenant = HttpContext.Current.Request.RequestContext.RouteData.DataTokens[DataTokens.ActiveTenant] as Tenant;
            Assert.IsNotNull(actualTenant);
            Assert.AreEqual<string>(TenantKey, actualTenant.Key);
        }

        /// <summary>
        /// 2) Configura template de URL com url de domínio padrão com key
        ///     Deve assegurar:
        ///     2.1) que acessar com url com token, irá ver theming do Tenant
        /// </summary>
        private void AssertThatParameteredUrlsWillShowTheTenantsCustomization()
        {
            // we set the configuration to parametered template ""
            var configEntry = new { Key = ConfigurationKeys.AppBaseDomain, Value = "http://localhost/{0}" };

            // creates the configuration entry
            Configurator.AddOrUpdateConfigurationEntry(configEntry.Key, configEntry.Value);

            // here is the tenant key we want to find
            const string TenantKey = "tenant-0099";
            var tenantForTest = NewTenantForTest(TenantKey);

            // var we create the mvcApplication that will react to the request
            this.TenantController.MockForTesting(
                string.Concat("http://localhost/", TenantKey),
                "ListTenants",
                HttpVerbs.Get);

            // create the tenant
            this.TenantController.CreateOrEditTenant(null, tenantForTest);

            // here we test if the tenant was correcly found from the url
            var mvcApplication = new MvcApplication(this.TenancyRepository);
            mvcApplication.ProcessRouteDataForTenancy();
            var containsTenantToken = HttpContext.Current.Request.RequestContext.RouteData.DataTokens.ContainsKey(DataTokens.ActiveTenant);
            Assert.IsTrue(containsTenantToken);

            var actualTenant = HttpContext.Current.Request.RequestContext.RouteData.DataTokens[DataTokens.ActiveTenant] as Tenant;
            Assert.IsNotNull(actualTenant);
            Assert.AreEqual<string>(TenantKey, actualTenant.Key);
        }
    }
}

